'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { adminApi } from '@/lib/api-client'
import { ArrowLeft, Save, Loader2 } from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'

interface Tool {
  id: string
  title: string
  description: string
  url: string
  deployPath?: string
  isDeployed: boolean
  status: 'PENDING' | 'APPROVED' | 'REJECTED'
  categoryId: string
  category: {
    id: string
    name: string
    icon: string
  }
  user: {
    name: string
  }
  createdAt: string
  originalFile?: string
  isExternal?: boolean
}

interface Category {
  id: string
  name: string
  icon: string
}

export default function EditToolPage() {
  const params = useParams()
  const router = useRouter()
  const toolId = params.id as string
  const { user, loading: authLoading } = useAuth()

  // 检查用户权限
  useEffect(() => {
    if (!authLoading && (!user || user.role !== 'ADMIN')) {
      router.push('/')
    }
  }, [user, authLoading, router])

  const [tool, setTool] = useState<Tool | null>(null)
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    url: '',
    categoryId: '',
    status: 'PENDING' as const
  })

  useEffect(() => {
    fetchToolAndCategories()
  }, [toolId])

  const fetchToolAndCategories = async () => {
    try {
      setLoading(true)
      
      // 获取工具信息
      const toolsResult = await adminApi.getTools()
      if (toolsResult.success) {
        const foundTool = toolsResult.data.find((t: any) => t.id === toolId)
        if (foundTool) {
          setTool({
            ...foundTool,
            isExternal: !foundTool.deployPath || foundTool.deployPath.trim() === ''
          })
          setFormData({
            title: foundTool.title,
            description: foundTool.description,
            url: foundTool.url,
            categoryId: foundTool.categoryId,
            status: foundTool.status
          })
        } else {
          console.error('工具不存在')
          router.push('/admin')
        }
      }

      // 获取分类列表
      const categoriesResult = await fetch('/api/categories')
      if (categoriesResult.ok) {
        const categoriesData = await categoriesResult.json()
        setCategories(categoriesData.data || [])
      }
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    try {
      setSaving(true)
      
      // 这里需要实现更新工具的API
      const updateData = {
        title: formData.title,
        description: formData.description,
        url: formData.url,
        categoryId: formData.categoryId,
        status: formData.status
      }

      // 临时使用fetch直接调用API
      const response = await fetch(`/api/admin/tools/${toolId}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(updateData)
      })

      if (response.ok) {
        router.push('/admin')
      } else {
        const error = await response.json()
        console.error('更新失败:', error.error)
        alert('更新失败: ' + error.error)
      }
    } catch (error) {
      console.error('更新失败:', error)
      alert('更新失败')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="flex items-center justify-center h-64">
          <Loader2 className="h-8 w-8 animate-spin" />
        </div>
      </div>
    )
  }

  if (!tool) {
    return (
      <div className="container mx-auto px-4 py-8">
        <Card>
          <CardContent className="p-6 text-center">
            <p className="text-gray-500">工具不存在</p>
            <Button className="mt-4" onClick={() => router.push('/admin')}>
              返回管理后台
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="max-w-2xl mx-auto">
        {/* 头部 */}
        <div className="flex items-center gap-4 mb-6">
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push('/admin')}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            返回
          </Button>
          <div>
            <h1 className="text-2xl font-bold">编辑工具</h1>
            <p className="text-gray-600">
              {tool.isExternal ? '外部工具' : '本地部署工具'} • 发布者: {tool.user.name}
            </p>
          </div>
        </div>

        {/* 编辑表单 */}
        <Card>
          <CardHeader>
            <CardTitle>工具信息</CardTitle>
            <CardDescription>
              编辑工具的基本信息和设置
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 工具标题 */}
            <div className="space-y-2">
              <Label htmlFor="title">工具标题</Label>
              <Input
                id="title"
                value={formData.title}
                onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                placeholder="输入工具标题"
              />
            </div>

            {/* 工具描述 */}
            <div className="space-y-2">
              <Label htmlFor="description">工具描述</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                placeholder="输入工具描述"
                rows={3}
              />
            </div>

            {/* 工具URL */}
            <div className="space-y-2">
              <Label htmlFor="url">工具URL</Label>
              <Input
                id="url"
                value={formData.url}
                onChange={(e) => setFormData(prev => ({ ...prev, url: e.target.value }))}
                placeholder="输入工具URL"
              />
            </div>

            {/* 分类 */}
            <div className="space-y-2">
              <Label htmlFor="category">分类</Label>
              <Select
                value={formData.categoryId}
                onValueChange={(value) => setFormData(prev => ({ ...prev, categoryId: value }))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择分类" />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((category) => (
                    <SelectItem key={category.id} value={category.id}>
                      {category.icon} {category.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 状态 */}
            <div className="space-y-2">
              <Label htmlFor="status">审核状态</Label>
              <Select
                value={formData.status}
                onValueChange={(value) => setFormData(prev => ({ ...prev, status: value as any }))}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="PENDING">待审核</SelectItem>
                  <SelectItem value="APPROVED">已审核</SelectItem>
                  <SelectItem value="REJECTED">已拒绝</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 工具信息显示 */}
            <div className="border-t pt-6">
              <h3 className="font-medium mb-4">工具信息</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                <div>
                  <span className="font-medium">工具类型:</span> {tool.isExternal ? '外部工具' : '本地部署'}
                </div>
                <div>
                  <span className="font-medium">部署状态:</span> {tool.isDeployed ? '已上线' : '已下线'}
                </div>
                {tool.deployPath && (
                  <div>
                    <span className="font-medium">部署路径:</span> {tool.deployPath}
                  </div>
                )}
                {tool.originalFile && (
                  <div>
                    <span className="font-medium">原始文件:</span> {tool.originalFile}
                  </div>
                )}
                <div>
                  <span className="font-medium">创建时间:</span> {new Date(tool.createdAt).toLocaleString()}
                </div>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-4 pt-6">
              <Button
                onClick={handleSave}
                disabled={saving}
                className="flex-1"
              >
                {saving ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    保存中...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    保存更改
                  </>
                )}
              </Button>
              <Button
                variant="outline"
                onClick={() => router.push('/admin')}
                disabled={saving}
              >
                取消
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
